import { creepNameToObj, objIDToObj } from "../../../tools/baseTools";
import { creepMoveExtesion, creepGetSource, pushCreepToTargetCreepList } from "../../../tools/tools/creepTool";

export default {
    init: function () {
        console.log('初始化运行逻辑');
    },
    /**rule运行逻辑
     * @param {Creep} creep 
     */
    run: function (creep) {
        creep = creepNameToObj(creep)
        if (creep.memory.state.isWorking) {
            // 工作逻辑
            ruleUpgraderWorking(creep)
        } else {
            // 准备逻辑
            creepGetSource({ creep: creep, room: Game.rooms[creep.memory.targetPos.roomName] })
        }
    }
}

function ruleUpgraderWorking(creep) {
    creep = creepNameToObj(creep)
    let targetObj = objIDToObj(creep.memory.targetID[creep.memory.targetID.length - 1])
    let resultCode = creep.upgradeController(targetObj)
    switch (resultCode) {
        case OK:
            if (creep.memory.state.isRuning) {
                let creepStateMemory = creep.memory.state
                creepStateMemory.isRuning = false
                creepStateMemory.isBlock = false
                creepStateMemory.path = null
                creepStateMemory.tick = 0
                targetObj.checkSelf()
            }
            break;
        case ERR_NOT_ENOUGH_RESOURCES:
            creep.memory.state.isWorking = false
            break;
        case ERR_NOT_IN_RANGE:
            creepMoveExtesion(creep)
            break;
        case ERR_NO_BODYPART:
            creep.say(`没有Work部件,羞愧难耐,算了自裁吧`)
            creep.suicide()
            break;
        case ERR_INVALID_TARGET:
            if (creep.memory.targetID.length == 0) {
                creep.memory.targetID.push(Game.rooms[creep.memory.targetPos.roomName].controller.id)
                pushCreepToTargetCreepList(creep)
            } else {
                creep.memory.targetID.pop()
            }
            break;
        default:
            console.log(creep.name+`使用upgradeController的逻辑可能出现问题了,错误编码${resultCode}`);
            break;
    }
}